#include "LabelButton.h"
#include <QLabel>
#include <QVBoxLayout>
#include "CircleButton.h"

//////////////////////////////////////
/// 上面是CicleButton, 下面是Label
//////////////////////////////////////
LabelButton::LabelButton(QWidget* parent)
    : QWidget(nullptr)
{
}

LabelButton::LabelButton(const QIcon& icon, const QString& name)
{
    const int MAX_HEIGHT = 80;
    const int MAX_WIDTH  = 70;
    this->setFixedSize(QSize(MAX_WIDTH, MAX_HEIGHT));
    this->setAttribute(Qt::WA_DeleteOnClose);
    /* 1. 初始化按钮 */
    avatar = new CircleButton();
    avatar->setIcon(icon);
    const QSize b_size = QSize(60, 60);
    avatar->setFixedSize(b_size);
    avatar->setIconSize(b_size);
    avatar->setStyleSheet(
        "QPushButton {"
        "border: none;"
        "}");
    /* 2. 初始化label, 当超过MAX_WIDTH会截断, 显示xxx... */
    name_label = new QLabel();
    name_label->setWordWrap(false);
    name_label->setFixedWidth(MAX_WIDTH);                                    // 需要设置固定宽度
    name_label->setAlignment(Qt::AlignHCenter);
    QFontMetrics metric(name_label->font());
    name_label->setText(metric.elidedText(name, Qt::ElideRight, MAX_WIDTH-5)); // 省略号在右侧出现
    name_label->setStyleSheet(
        "QLabel {"
        "font-size: 14px;"
        "}");
    // 下面是手动计算的代码, 这样写并不好, 不如上面的直接调用Qt的函数
    // 可显示的字符数(new_width) = 可用宽度(available_width) / 一个字符的宽度(char_width)
    // char_width = 总宽度(total_width) / 总字符数(L)
    // 可得new_width = L * available_width / total_width
    // QFontMetrics metrics(name_label->font());
    // int orignal_width = metrics.horizontalAdvance(name); // 名字的原始水平宽度
    // if(orignal_width > MAX_WIDTH - 3) {
    //     int tail_width = metrics.horizontalAdvance("..."); // ...的水平宽度
    //     int avalible_width = MAX_WIDTH - tail_width; // 可用的宽度
    //     int new_width = name.length() * avalible_width / orignal_width;
    // }
    /* 3. 设置布局 */
    QVBoxLayout* v_layout = new QVBoxLayout();
    this->setLayout(v_layout);
    v_layout->setContentsMargins(0, 0, 0, 0);
    v_layout->setSpacing(5);
    v_layout->addWidget(avatar, 0, Qt::AlignHCenter);
    v_layout->addWidget(name_label, 0);
}

CircleButton *LabelButton::get_button()
{
    return avatar;
}
